package egovframework.npqs.pqi.mobile.activity.disinfection;

import java.util.ArrayList;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.drawable.Drawable;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.Window;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.RadioButton;
import android.widget.RelativeLayout;
import android.widget.RelativeLayout.LayoutParams;
import android.widget.TextView;
import android.widget.Toast;
import egovframework.npqs.pqi.mobile.AppStatus;
import egovframework.npqs.pqi.mobile.R;
import egovframework.npqs.pqi.mobile.activity.approve.ApproveDetail;
import egovframework.npqs.pqi.mobile.jsoncontent.DisinfecResultDetailItem;
import egovframework.npqs.pqi.mobile.jsoncontent.ErrorItem;
import egovframework.npqs.pqi.mobile.jsoncontent.listitem.QuarRsltDtailItem;
import egovframework.npqs.pqi.mobile.jsonparser.DisinfectionStatusDetailThread;
import egovframework.npqs.pqi.mobile.jsonparser.DisinfectionStatusDetailThread.DisinfectionStatusDetailThreadCallback;

//소독현황상세(소독결과현황상세)
public class DisinfectionStatusDetailActivity extends Activity implements OnClickListener
				, DisinfectionStatusDetailThreadCallback, OnItemSelectedListener{
	private TextView titleTxt;	// 상단 타이틀
	private AppStatus myapp;
	private Context context;
	private String resNo, recNo, offCd;
	
	private ImageButton upBtn, downBtn, searchBtn, btnHome, btn_back;
	
	private EditText offCdEdit, requestNumEdit, edit_request_num;	// 검역신청검역지 코드 에디트 박스, 검역신청 상세번호 에디트 박스
	
	private ListView listView;
	private DisinfectionDetailListAdapter disinfectionDetailListAdapter;
	
	private TextView headerTotTxt, navigation;
	private TextView content1_1, content1_2, content2_1, content2_2;
	private TextView content3_1, content4_1, content4_2, content5_1;
	private TextView content6_1, content6_2, content7_1, content8_1;
	private TextView content9_1, content9_2, content10_1, content11_1;
	private TextView content12_1, content13_1, content_title_13_1;
	private RadioButton chk_Y, chk_N;
	
	private DisinfecResultDetailItem disfecResultItem;
	private DisinfectionStatusDetailThread disfecThread;
	private ArrayList<QuarRsltDtailItem> prodArrList;
	
	private Button footerBtn01, footerBtn02, footerBtn03, footerBtn04;	// 하단 버튼
	private final static int MSG_QUARANTINE_COMPLETED = 0;
	private final static int MSG_QUARANTINE_ERROR = 1;
	private final static int MSG_NETWORK_ERROR = 2;
	
	//하단 리스트 해더
	private LinearLayout list_header_Layout;
	
	private boolean value;
	
	//사진
	private RelativeLayout photo_check_mgs, detail_layout13_1;
	private ImageView photo_view, photo_view2;
	private Drawable drawable1, drawable2;
	private String url1, url2;
	
	private String mResult;
	
	/* G-MOBILE 변수*/
    private String temp;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		AppStatus.navigation.addPathLocation("소독현황상세");
		requestWindowFeature(Window.FEATURE_NO_TITLE);
		setContentView(R.layout.activity_disinfection_status_detail);
		
		Intent intent = getIntent();
		offCd = intent.getStringExtra("offCd");
		resNo = intent.getStringExtra("resNo");
		recNo = intent.getStringExtra("recNo");
		value = false;
		init();
	}
	
	private void init(){
		context = this;
		myapp = (AppStatus) getApplicationContext();
		myapp.startBroker(context);
		
		titleTxt = (TextView)findViewById(R.id.headerTitleText);
		titleTxt.setText("소독현황상세");
		
		navigation = (TextView)findViewById(R.id.navigation);
		navigation.setText(AppStatus.navigation.getPath());
		Log.i("AppStatus.navigation.getPath()->", AppStatus.navigation.getPath());
		
		//하단 리스트 해더
		list_header_Layout = (LinearLayout)findViewById(R.id.list_header_Layout);
		list_header_Layout.setVisibility(View.VISIBLE);
		
		offCdEdit = (EditText)findViewById(R.id.edit_offcd);
		offCdEdit.setText(offCd);
		
		requestNumEdit = (EditText)findViewById(R.id.edit_request_num);
		//requestNumEdit.setText(resNo);
		requestNumEdit.setText(recNo);
		
		searchBtn = (ImageButton)findViewById(R.id.search_btn);
		searchBtn.setOnClickListener(this);
		
		/*loginBtn = (ImageButton)findViewById(R.id.btnLogin);
		loginBtn.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				myapp.appFinish(DisinfectionStatusDetailActivity.this);		
			}
		});*/
		
		btn_back = (ImageButton)findViewById(R.id.btn_back);
		btn_back.setVisibility(View.VISIBLE);
		btn_back.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				onBackPressed();
			}
		});
		
		btnHome = (ImageButton)findViewById(R.id.btnHome);
		btnHome.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				myapp.setAbleHome(true);
				finish();
			}
		});
		
		listView = (ListView)findViewById(R.id.dis_detail_list);
		disinfectionDetailListAdapter = new DisinfectionDetailListAdapter();
		
		footerBtn01 = (Button)findViewById(R.id.footer01Btn);
		footerBtn02 = (Button)findViewById(R.id.footer02Btn);
		footerBtn03 = (Button)findViewById(R.id.footer03Btn);
		footerBtn04 = (Button)findViewById(R.id.footer04Btn);
		
		content1_1 = (TextView)findViewById(R.id.content_1_1);
		content1_2 = (TextView)findViewById(R.id.content_1_2);
		content2_1 = (TextView)findViewById(R.id.content_2_1);
		content2_2 = (TextView)findViewById(R.id.content_2_2);
		content3_1 = (TextView)findViewById(R.id.content_3_1);
		content4_1 = (TextView)findViewById(R.id.content_4_1);
		content4_2 = (TextView)findViewById(R.id.content_4_2);
		content5_1 = (TextView)findViewById(R.id.content_5_1);
		content6_1 = (TextView)findViewById(R.id.content_6_1);
		content6_2 = (TextView)findViewById(R.id.content_6_2);
		content7_1 = (TextView)findViewById(R.id.content_7_1);
		content8_1 = (TextView)findViewById(R.id.content_8_1);
		content9_1 = (TextView)findViewById(R.id.content_9_1);
		content9_2 = (TextView)findViewById(R.id.content_9_2);
		content10_1 = (TextView)findViewById(R.id.content_10_1);
		content11_1 = (TextView)findViewById(R.id.content_11_1);
		content_title_13_1 = (TextView)findViewById(R.id.content_title_13_1);
		
		chk_Y = (RadioButton)findViewById(R.id.chk_y);
		chk_N = (RadioButton)findViewById(R.id.chk_n);
		content12_1 = (TextView)findViewById(R.id.content_12_1);
		content13_1 = (TextView)findViewById(R.id.content_13_1);
		
		edit_request_num=(EditText)findViewById(R.id.edit_request_num); 						//검역신청번호 뒷자리
		
		//사진
		detail_layout13_1 = (RelativeLayout)findViewById(R.id.detail_layout13_1);
		photo_check_mgs = (RelativeLayout)findViewById(R.id.photo_check_mgs);
		photo_view = (ImageView)findViewById(R.id.photo_view);
		photo_view2 = (ImageView)findViewById(R.id.photo_view2);
		
		//footerBtn01.setOnClickListener(this);
		footerBtn01.setBackgroundResource(R.drawable.f_blank_sel);
		footerBtn02.setOnClickListener(this);
		footerBtn03.setOnClickListener(this);
		footerBtn04.setOnClickListener(this);
		
		searchDetail();
	}
	
	private void searchDetail(){
		
		myapp.showDialogNo(context);
		temp = "조건검색";
		myapp.utilm.InputKeybordHidden(context, requestNumEdit);
		myapp.utilm.InputKeybordHidden(context, offCdEdit);
		//asyncTaskIsConnectedVPN();
		threadStart();
	}
	
	public void threadStart(){
		if("조건검색".equals(temp)){
    		if(value){
    			//검색으로 하면 recNo가 넘어가야한다
    			disfecThread = new DisinfectionStatusDetailThread(context, this
    					, requestNumEdit.getText().toString(), offCdEdit.getText().toString()
    					, true, AppStatus.getmUserId());
    			value = false;
    		}else{
    			//리스트에서 상세로 넘어오면 소독결과번호로 조회하여야 한다.
    			disfecThread = new DisinfectionStatusDetailThread(context, this, resNo
    					, offCdEdit.getText().toString(), false, AppStatus.getmUserId());
    		}
    		disfecThread.start();
    	}
	}
	
	private void layoutSetting() {
		content1_1.setText(disfecResultItem.getVenCd());
		content1_2.setText(disfecResultItem.getVenNm());
		content2_1.setText(disfecResultItem.getDsnfResOffCd() +"-"+disfecResultItem.getDsnfResNo());
		content2_2.setText(disfecResultItem.getPasDe());
		content3_1.setText(disfecResultItem.getDsnfInspctPlace());
		content5_1.setText(disfecResultItem.getAntDatefr() +"~"+ disfecResultItem.getAntDateto());
		content6_1.setText(disfecResultItem.getAntMetNm());
		content6_2.setText(disfecResultItem.getAntMin());
		content7_1.setText(disfecResultItem.getEquKindNm());
		content8_1.setText(disfecResultItem.getMedNm());
		content9_1.setText(disfecResultItem.getMedQty());
		content9_2.setText(disfecResultItem.getRooTemp());
		content10_1.setText(disfecResultItem.getAntMet());
		content11_1.setText(disfecResultItem.getFumQty());
		content12_1.setText(disfecResultItem.getMedNamNm1() +"   "+ disfecResultItem.getMedNamNm2());
		content13_1.setText(disfecResultItem.getOpeNamNm1() +"   "+ disfecResultItem.getOpeNamNm2());
		content_title_13_1.setText("개방입회검역관");
		
		if(disfecResultItem.getRotDiv().equals("N") ){
			chk_Y.setChecked(false);
			chk_N.setChecked(true);
		}else{
			chk_Y.setChecked(true);
			chk_N.setChecked(false);
		}
		
		//사진보기
		if("".equals(disfecResultItem.getImgResult1().trim())){
			url1="";
		}else{
			detail_layout13_1.setVisibility(View.VISIBLE);
			photo_check_mgs.setVisibility(View.GONE);
			photo_view.setVisibility(View.VISIBLE);
			url1 = myapp.cameraUtil.photoSetting(disfecResultItem.getImgResult1()).replace("\\", "/");
			new yourTask().execute();
		}
		if("".equals(disfecResultItem.getImgResult2().trim())){
			url2 = "";
		}else{
			photo_view2.setVisibility(View.VISIBLE);
			url2 = myapp.cameraUtil.photoSetting(disfecResultItem.getImgResult2()).replace("\\", "/");
			new yourTask().execute();
		}
		
		listView.setVisibility(View.VISIBLE);
		prodArrList = disfecResultItem.getItems();
		
		headerTotTxt = (TextView)findViewById(R.id.header_tot);
		upBtn = (ImageButton)findViewById(R.id.header_up_btn);
		downBtn = (ImageButton)findViewById(R.id.header_down_btn);

		headerTotTxt.setText("총 품목:"+disfecResultItem.getItemsResult()+"건");
		
		listView.setAdapter(disinfectionDetailListAdapter);
		
		upBtn.setOnClickListener(this);
		downBtn.setOnClickListener(this);
		downBtn.performClick();
		
		
	}
	
	private class yourTask extends AsyncTask<Integer, Void, Integer> {
	    @Override
	    protected void onPreExecute() {
	        super.onPreExecute();
	        //show a progress bar
	    }
	    @Override
	    protected Integer doInBackground(Integer... params) {
	        drawable1  =  myapp.cameraUtil.LoadImageFromWeb(url1); 
	        drawable2  =  myapp.cameraUtil.LoadImageFromWeb(url2); 
	        return 0; 
	    }      
	    @Override
	    protected void onPostExecute(Integer result) {
	        super.onPostExecute(result);
	        photo_view.setImageDrawable(drawable1);   
	        photo_view2.setImageDrawable(drawable2);  
	    }
	}
	
	private void moveApprove(){
		Intent intent = new Intent(DisinfectionStatusDetailActivity.this, ApproveDetail.class);
		
		if(prodArrList.size() == 1){
			intent.putExtra("resNo", prodArrList.get(0).getResNo());
			intent.putExtra("resOffCd", prodArrList.get(0).getResOffCd());
			intent.putExtra("value", "0");	
		}else{
			String fullResNo ="";
			for (int i = 0; i < prodArrList.size(); i++) {
				if(fullResNo.equals("")){
					fullResNo = prodArrList.get(i).getResOffCd() +"-"+prodArrList.get(i).getResNo();
				}else{
					fullResNo += ","+prodArrList.get(i).getResOffCd() +"-"+prodArrList.get(i).getResNo();
				}
			}
			intent.putExtra("fullResNo", fullResNo);
			intent.putExtra("value", "1");
		}
		startActivity(intent);
	}

	@Override
	public void onClick(View v) {
		Intent intent ;
		switch (v.getId()) {
		
		case R.id.search_btn:
			if(edit_request_num.getText().toString().length()==8){
				value=true;
				searchDetail();
			}else{
				myapp.utilm.ShowDialog(DisinfectionStatusDetailActivity.this, "실패", "검역신청 번호 뒤 8자리를 입력해 주세요.", 20);
			}
			break;
		
		case R.id.footer01Btn:	// 목록 버튼
			onBackPressed();
			break;
			
		case R.id.footer03Btn:	// 결재버튼
			if(!prodArrList.get(0).getFullDsnfResNo().equals("")){
				if(prodArrList.get(0).getDocScrtySe().equals("Y")){
					moveApprove();
				}else{
					new AlertDialog.Builder(DisinfectionStatusDetailActivity.this)
					.setTitle("실패")
					.setMessage("서류미보완 상태입니다. 결재시 서류보완도 완료됩니다.그래도 결재하시겠습니까?")
					.setPositiveButton("확인", new DialogInterface.OnClickListener() {
						@Override
						public void onClick(DialogInterface dialog, int which) {
							try {
								moveApprove();
								dialog.dismiss();
							} catch (Exception e) {}
						}
					})
					.setNegativeButton("취소", new DialogInterface.OnClickListener() {
						@Override
						public void onClick(DialogInterface dialog, int which) {
							dialog.dismiss();
						}
					})
					.setCancelable(false)
					.show();
				}
			}else{
				myapp.utilm.ShowDialog(DisinfectionStatusDetailActivity.this, "실패", "저장후 결재하실수 있습니다.", 20);
				return;
			}
			break;
			
		case R.id.header_up_btn:
			RelativeLayout.LayoutParams listParams = new RelativeLayout.LayoutParams
		    (LayoutParams.WRAP_CONTENT, myapp.utilm.getDpToPixel(context, 400));
			listParams.addRule(RelativeLayout.ABOVE, R.id.bottom_layout);
			listView.setLayoutParams(listParams);
			break;
		case R.id.header_down_btn:
			RelativeLayout.LayoutParams listParams1 = new RelativeLayout.LayoutParams
		    (LayoutParams.WRAP_CONTENT, myapp.utilm.getDpToPixel(context, 120));
			listParams1.addRule(RelativeLayout.ABOVE, R.id.bottom_layout);
			listView.setLayoutParams(listParams1);
			break;			

		default:
			break;
		}
		
	}

	@Override
	public void OnDisinfectionStatusDetailCompleted(boolean isNetworkConntected,
			DisinfecResultDetailItem quarantineItem, String message) {
		Log.i("message-->", "message-->"+message);
		if(null != message && !"".equals(message)){
			mResult = message;
			reesultToast();
		}
		
		if(myapp.dialog !=null && myapp.dialog.isShowing()) {
			myapp.dialog.dismiss();
		}
		
		if(!isNetworkConntected){	// 네트워크 접속이 되어 있지 않을 때
			Message msg = handler.obtainMessage();
			msg.what = MSG_NETWORK_ERROR;
			handler.sendMessage(msg);
			return;
		}
		
		if(quarantineItem != null) {
			this.disfecResultItem = quarantineItem;
			Message msg = handler.obtainMessage();
			msg.what = MSG_QUARANTINE_COMPLETED;
			handler.sendMessage(msg);
		}	
		
	}

	@Override
	public void OnDisinfectionStatusDetailError(ErrorItem errorItem) {
		if(myapp.dialog !=null && myapp.dialog.isShowing()) {
			myapp.dialog.dismiss();
		}

		Message msg = handler.obtainMessage();
		msg.what = MSG_QUARANTINE_ERROR;
		if(errorItem != null) {
			msg.obj = errorItem.getrDesc();
		}
		handler.sendMessage(msg);	
		
	}
	
	private Handler handler = new Handler() {
		@Override
		public void handleMessage(final Message msg) {
			switch (msg.what) {
			case MSG_QUARANTINE_COMPLETED:
				layoutSetting();
				break;

			case MSG_QUARANTINE_ERROR:
				String errMsg = "";
				if(msg == null ||msg.obj.toString().equals("")){
					errMsg = "서버와의 연결에 실패하였습니다.";
				}else{
					errMsg = msg.obj.toString();	
				}
				listView.setVisibility(View.GONE);
				myapp.utilm.ShowDialog(DisinfectionStatusDetailActivity.this, "실패", errMsg, 20);
				
				break;

			case MSG_NETWORK_ERROR:
				myapp.utilm.ShowDialog(DisinfectionStatusDetailActivity.this, "실패", "네트워크에러", 20);

			default:
				break;
			}
		}
	};
	
	class DisinfectionDetailListAdapter extends BaseAdapter {
		TextView txtRecNo, txtResNo, txtInOut, txtDocument;
		TextView txtProdSeq, txtProdName, txtInsCnt, txtAntCnt;
		
		@Override
		public int getCount() {
			return prodArrList.size();
		}

		@Override
		public Object getItem(int position) {
			return prodArrList.get(position);
		}

		@Override
		public long getItemId(int position) {
			return position;
		}

		@Override
		public View getView(final int position, View convertView, ViewGroup parent) {
			if (convertView == null || convertView != null) {
    			LayoutInflater inflater = (LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
    			convertView = inflater.inflate(R.layout.list_dis_status_detail_item, parent, false);
    		}
			
			txtRecNo = (TextView)convertView.findViewById(R.id.detail_rec_no);
			txtResNo = (TextView)convertView.findViewById(R.id.detail_res_no);
			txtInOut = (TextView)convertView.findViewById(R.id.detail_in_out);
			txtProdSeq = (TextView)convertView.findViewById(R.id.detail_prod_seq);
			txtProdName = (TextView)convertView.findViewById(R.id.detail_prod_name);
			txtInsCnt = (TextView)convertView.findViewById(R.id.detail_ins_cnt);
			txtAntCnt = (TextView)convertView.findViewById(R.id.detail_ant_cnt);
			txtDocument = (TextView)convertView.findViewById(R.id.detail_document);
			
			txtRecNo.setText(prodArrList.get(position).getFullRecNo());
			txtResNo.setText(prodArrList.get(position).getFullDsnfResNo());
			txtInOut.setText(prodArrList.get(position).getNatNm());
			txtProdSeq.setText(prodArrList.get(position).getRecSeq());
			txtProdName.setText(prodArrList.get(position).getFullPrdlstNm());
			txtInsCnt.setText(prodArrList.get(position).getInsQty());
			txtAntCnt.setText(prodArrList.get(position).getAntQty());
			txtDocument.setText(prodArrList.get(position).getDocScrtySe());
			
			convertView.setOnClickListener(new OnClickListener() {
				
				@Override
				public void onClick(View v) {
					listItemClickEvent(position);
				}
			});
			
			return convertView;
		}
		
		private void listItemClickEvent(final int position) {}
	}

	@Override
	public void onItemSelected(AdapterView<?> parent, View view, int position,
			long id) {}

	@Override
	public void onNothingSelected(AdapterView<?> parent) {}
	
	@Override
	protected void onResume() {
		if(myapp.isFinishState()||myapp.isAbleHome()){
			finish();
		}
		if(myapp.isDataDetailLoadState()){
			myapp.startBroker(context);
			layoutSetting();
			myapp.setDataDetailLoadState(false);
		}
		super.onResume();
	}
	
	/*@Override
	protected void onRestart() {
		searchBtn.performClick();
		super.onRestart();
	}*/
	
	@Override
	protected void onDestroy() {
		super.onDestroy();
		AppStatus.navigation.delPathLocation();
	}
	
	private void reesultToast() {
		runOnUiThread(new Runnable() {

            public void run() {
                Toast toast = Toast.makeText(context, mResult, Toast.LENGTH_SHORT);
                toast.setGravity(Gravity.CENTER, 0, 50);
                toast.show();
            }
        });
    }
	
}
